public class Answer3 {
    // 孩子们的游戏
    //https://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6?tpId=13&tqId=11199&ru=/exam/oj
    public static void main(String[] args) {
        System.out.println(LastRemaining_Solution(5, 3));
    }

    public static int LastRemaining_Solution (int n, int m) {
        boolean[] dp =new boolean[n];
        int num=n;
        int x=0;
        int y=m;
        while(num-- !=1){
            while(y-- != 1 || num-- !=1){
                if(dp[x]){
                    y++;
                }
                x++;
                if(x>=n) x%=n;
            }
            dp[x]=true;
            y=m;
        }
        for(int i=0;i<n;i++){
            if(!dp[i]){
                return i;
            }
        }
        return 3;
    }











    public int LastRemaining_Solution1 (int n, int m) {

        int f=0;
        for(int i=2;i<=n;i++){
            f=(f+m)%i;
        }
        return f;
    }
}
